#include "key_common.h"
#include <stdio.h>
#include <gpiod.h>

/**
 * 初始化GPIO芯片和线
 * @param chip_label: GPIO芯片标签
 * @param line_num: GPIO线号
 * @param consumer: 消费者名称
 * @return: 初始化成功返回GPIO线指针，失败返回NULL
 */
struct gpiod_line *gpio_init(const char *chip_label, unsigned int line_num, const char *consumer)
{
    struct gpiod_chip *chip = gpiod_chip_open_by_label(chip_label);
    if (!chip)
    {
        perror("打开GPIO芯片失败！");
        return NULL;
    }

    struct gpiod_line *line = gpiod_chip_get_line(chip, line_num);
    if (!line)
    {
        perror("获取GPIO线失败！");
        gpiod_chip_close(chip);
        return NULL;
    }

    if (gpiod_line_request_input(line, consumer))
    {
        perror("请求将GPIO线设置为输入模式失败！");
        gpiod_chip_close(chip);
        return NULL;
    }

    return line;
}
